package com.kaaction.modules.eb.api;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.kaaction.common.utils.StringUtils;
import com.kaaction.common.web.BaseController;
import com.kaaction.modules.eb.entity.Order;
import com.kaaction.modules.eb.entity.OrderProduct;
import com.kaaction.modules.eb.entity.Product;
import com.kaaction.modules.eb.service.OrderProductService;
import com.kaaction.modules.eb.service.OrderService;
import com.kaaction.modules.eb.service.ProductService;
import com.kaaction.modules.market.entity.Event;
import com.kaaction.modules.market.service.EventService;

@Controller
@RequestMapping(value = "/api/v1/eb/order")
public class OrderApiController extends BaseController{

	/**
	 * 日志对象
	 */
	protected Logger logger = Logger.getLogger(this.getClass());

	@Autowired
	private OrderService orderService;

	@Autowired
	private OrderProductService orderProductService;

	@Autowired
	private EventService eventService;

	@Autowired
	private ProductService productService;

	@RequestMapping(value = { "log" })
	public void log(HttpServletRequest request, HttpServletResponse response) throws IOException {
		logger.info("random is : " + (int) (Math.random() * 1000000));
	}
	
	/**
	 * 我的订单（已完成）
	 */
	@RequestMapping(value = { "mine" })
	public void mine(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setHeader("Access-Control-Allow-Origin", "*");
		String customerId = request.getParameter("customerId");
		List<Order> orderList = orderService.getOrderByCustomerId(customerId,"020");
		super.writeAjaxResponse(response,orderList);
	}

	/**
	 * 新增订单，以及订单与商品的对应关系
	 */
	@RequestMapping(value = { "add" })
	public void add(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setHeader("Access-Control-Allow-Origin", "*");
		String eventId = request.getParameter("eventId");
		String productId = request.getParameter("productId");
		String buyNum = request.getParameter("buyNum");
		String productSize = request.getParameter("productSize");

		String addressProvince = request.getParameter("addressProvince");
		String addressCity = request.getParameter("addressCity");
		String addressCounty = request.getParameter("addressCounty");
		String addressMore = request.getParameter("addressMore");

		String recipientName = request.getParameter("recipientName");
		String recipientMobile = request.getParameter("recipientMobile");
		String remarks = request.getParameter("userRemarks");

		logger.info("活动编号 = " + eventId);
		logger.info("商品编号 = " + productId);
		logger.info("recipientName = " + recipientName);
		logger.info("addressProvince = " + addressProvince);
		logger.info("buyNum = " + buyNum);

		// TODO:放到service层，1个事务中
		int buyNumInt = 0;
		if(!StringUtils.isBlank(buyNum)){
			buyNumInt = Integer.parseInt(buyNum);
		}
		double totalFee = 0.0;
		logger.info("get more info from table : product");
		Product product = productService.get(productId);
		if (product != null && product.getSellPrice() != null) {
			logger.info("商品不为空");
			double singleProductPrice = product.getSellPrice();
			totalFee = singleProductPrice * buyNumInt;
			logger.info("单价:"+singleProductPrice + ",购买数量:"+buyNumInt);
			// 1.生成1条订单记录
			Order order = new Order();
			String orderCode = StringUtils.getUniqueString();
			order.setOrderCode(orderCode);
			order.setProductTotalFee(totalFee);
			order.setStatus("010");
			Date now = new Date();
			order.setCreateDate(now);
			order.setUpdateDate(now);
			order.setRecipientAddress(addressProvince + addressCity + addressCounty + addressMore);
			order.setDelFlag("0");

			order.setRecipientContact(recipientMobile);
			order.setRecipientName(recipientName);
			order.setRemarks(remarks);
			logger.info("order detail is:");
			logger.info("recipientMobile = " + recipientMobile);
			logger.info("recipientName = " + recipientName);
			orderService.save(order);
			logger.info("save order successfully,update recipient info...");

			// 2.生成商品与订单对应关系
			OrderProduct orderProduct = new OrderProduct();
			orderProduct.setProduct(product);
			orderProduct.setOrder(order);
			orderProduct.setProductPrice(product.getSellPrice());
			orderProduct.setProductQuantity(buyNumInt);
			orderProduct.setProductTotalPrice(totalFee);
			orderProduct.setStatus("0");
			orderProduct.setCreateDate(now);
			orderProduct.setUpdateDate(now);
			orderProduct.setDelFlag("0");
			orderProduct.setProductSize(productSize);
			orderProductService.save(orderProduct);
			logger.info("save order<->product successfully,update recipient info...");

			PrintWriter pw = response.getWriter();

			pw.write(JSON.toJSONString(order, SerializerFeature.DisableCircularReferenceDetect));
			pw.flush();
			pw.close();
		}
	}
}
